export interface TokenInfo {
  address: string;
  symbol: string;
  name: string;
  decimals: number;
  logoURI?: string;
  balance: string;
}

export interface TokenList {
  name: string;
  timestamp: string;
  version: {
    major: number;
    minor: number;
    patch: number;
  };
  tokens: TokenInfo[];
}

export class TokenManager {
  private tokens: Map<string, TokenInfo> = new Map();
  private tokenLists: TokenList[] = [];

  constructor() {
    this.loadDefaultTokens();
  }

  // 加载默认代币列表
  private loadDefaultTokens(): void {
    const defaultTokens: TokenInfo[] = [
      {
        address: '0xA0b86a33E6441b8C4C8C0E4A0b86a33E6441b8C4C',
        symbol: 'USDT',
        name: 'Tether USD',
        decimals: 6,
        balance: '0'
      },
      {
        address: '0xB0b86a33E6441b8C4C8C0E4A0b86a33E6441b8C4C',
        symbol: 'USDC',
        name: 'USD Coin',
        decimals: 6,
        balance: '0'
      },
      {
        address: '0xC0b86a33E6441b8C4C8C0E4A0b86a33E6441b8C4C',
        symbol: 'DAI',
        name: 'Dai Stablecoin',
        decimals: 18,
        balance: '0'
      }
    ];

    defaultTokens.forEach(token => {
      this.tokens.set(token.address.toLowerCase(), token);
    });
  }

  // 添加代币
  addToken(token: TokenInfo): void {
    this.tokens.set(token.address.toLowerCase(), token);
  }

  // 移除代币
  removeToken(address: string): void {
    this.tokens.delete(address.toLowerCase());
  }

  // 获取代币信息
  getToken(address: string): TokenInfo | undefined {
    return this.tokens.get(address.toLowerCase());
  }

  // 获取所有代币
  getAllTokens(): TokenInfo[] {
    return Array.from(this.tokens.values());
  }

  // 更新代币余额
  async updateTokenBalance(address: string, userAddress: string, provider: any): Promise<void> {
    const token = this.tokens.get(address.toLowerCase());
    if (!token) return;

    try {
      // ERC20代币余额查询
      const contract = new ethers.Contract(
        address,
        [
          'function balanceOf(address owner) view returns (uint256)',
          'function decimals() view returns (uint8)',
          'function symbol() view returns (string)',
          'function name() view returns (string)'
        ],
        provider
      );

      const balance = await contract.balanceOf(userAddress);
      const decimals = await contract.decimals();
      
      token.balance = ethers.formatUnits(balance, decimals);
    } catch (error) {
      console.error('更新代币余额失败:', error);
      token.balance = '0';
    }
  }

  // 获取代币价格（需要集成价格API）
  async getTokenPrice(symbol: string): Promise<number> {
    try {
      // 这里可以集成CoinGecko、CoinMarketCap等价格API
      const response = await fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${symbol}&vs_currencies=usd`);
      const data = await response.json();
      return data[symbol]?.usd || 0;
    } catch (error) {
      console.error('获取代币价格失败:', error);
      return 0;
    }
  }

  // 搜索代币
  searchTokens(query: string): TokenInfo[] {
    const lowerQuery = query.toLowerCase();
    return Array.from(this.tokens.values()).filter(token =>
      token.name.toLowerCase().includes(lowerQuery) ||
      token.symbol.toLowerCase().includes(lowerQuery) ||
      token.address.toLowerCase().includes(lowerQuery)
    );
  }

  // 验证代币地址
  isValidTokenAddress(address: string): boolean {
    return ethers.isAddress(address);
  }

  // 获取代币元数据
  async getTokenMetadata(address: string, provider: any): Promise<Partial<TokenInfo> | null> {
    try {
      const contract = new ethers.Contract(
        address,
        [
          'function decimals() view returns (uint8)',
          'function symbol() view returns (string)',
          'function name() view returns (string)'
        ],
        provider
      );

      const [decimals, symbol, name] = await Promise.all([
        contract.decimals(),
        contract.symbol(),
        contract.name()
      ]);

      return {
        address: address.toLowerCase(),
        decimals,
        symbol,
        name
      };
    } catch (error) {
      console.error('获取代币元数据失败:', error);
      return null;
    }
  }

  // 导入代币列表
  async importTokenList(url: string): Promise<void> {
    try {
      const response = await fetch(url);
      const tokenList: TokenList = await response.json();
      this.tokenLists.push(tokenList);
      
      // 添加代币到管理器
      tokenList.tokens.forEach(token => {
        this.tokens.set(token.address.toLowerCase(), token);
      });
    } catch (error) {
      console.error('导入代币列表失败:', error);
    }
  }

  // 获取代币列表
  getTokenLists(): TokenList[] {
    return this.tokenLists;
  }
}
